package com.example.demo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.deepoove.poi.XWPFTemplate;
import com.example.demo.dto.AttendanceDto;
import com.example.demo.dto.UserInfoDto;
import com.example.demo.listener.AttendanceListener;
import com.example.demo.listener.UserInfoListener;
import com.example.demo.mapper.JjrMapper;
import com.example.demo.service.AttendanceService;
import com.example.demo.vo.JinSanJjrVo;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author DUYULONG
 * @date 2023/11/22 15:11
 */
@Service
public class AttendanceServiceImpl implements AttendanceService {
    private final ExecutorService executorService = new ThreadPoolExecutor(2, 100, 60L, TimeUnit.SECONDS, new SynchronousQueue());
    @Resource
    private JjrMapper jjrMapper;

    @Override
    public void excel(MultipartFile file, String startTime, String endTime, List<String> userList) throws IOException, InterruptedException {
//        String sheetName = null;
//
//        ExcelReader excelReader = null;
//        List<AttendanceListener> listenerList = new ArrayList<>();
//        Map<String, AttendanceListener> listenerMap = new HashMap<>();
//        try {
//            excelReader = EasyExcel.read(file.getInputStream()).build();
//            List<ReadSheet> sheetList = excelReader.excelExecutor().sheetList();
//
//            for (int i = 0; i < sheetList.size(); i++) {
//                sheetName = sheetList.get(i).getSheetName();
//
//                AttendanceListener listener = new AttendanceListener(startTime, endTime, userList);
//                ReadSheet build = EasyExcel.readSheet(i)
//                        .head(AttendanceDto.class)
//                        .registerReadListener(listener)
//                        .headRowNumber(1).build();
//                excelReader.read(build);
//                listenerList.add(listener);
//                listenerMap.put(sheetName, listener);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            excelReader.finish();
//        }
        AttendanceListener listener = new AttendanceListener(startTime, endTime, userList);
        EasyExcel.read(file.getInputStream())
                .head(AttendanceDto.class)
                .registerReadListener(listener)
                .doReadAll();

        List<AttendanceDto> dataList = listener.getDataList();
        Map<String, Integer> removeMap = new HashMap<>();
        List<List<AttendanceDto>> partition = ListUtils.partition(dataList, 2000);
        CountDownLatch latch = new CountDownLatch(partition.size());
        for (List<AttendanceDto> attendanceDtos : partition) {
            executorService.submit(() -> {
                AtomicInteger size = new AtomicInteger(attendanceDtos.size());
                attendanceDtos.stream().forEach(e -> {
                    Boolean holiday = isHoliday(e.getRq());
                    if (!holiday && !StringUtils.hasText(e.getTime1())) {
                        randomTime1(e);
                    }
                    if (!holiday && !StringUtils.hasText(e.getTime2())) {
                        randomTime2(e);
                    }
                    if (!StringUtils.hasText(e.getTime1()) && StringUtils.hasText(e.getTime2())) {
                        randomTime1(e);
                    }
                    if (StringUtils.hasText(e.getTime1()) && !StringUtils.hasText(e.getTime2())) {
                        randomTime2(e);
                    }
                    if (holiday && !StringUtils.hasText(e.getTime1()) && !StringUtils.hasText(e.getTime2())) {
                        removeMap.put(e.getUsername()+"_"+e.getRq(), 1);
                    }
                    System.out.println(Thread.currentThread().getName()+": "+ size.getAndDecrement());
                });
                latch.countDown();
            });
        }
        latch.await();

        //删除节假日未加班的数据
        Iterator<AttendanceDto> iterator = dataList.iterator();
        while (iterator.hasNext()) {
            AttendanceDto next = iterator.next();
            if (removeMap.containsKey(next.getUsername()+"_"+next.getRq())) {
                iterator.remove();
            }
        }

        //导出
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "no-store");
        response.addHeader("Cache-Control", "max-age=0");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+file.getOriginalFilename()+".xlsx");
        EasyExcel.write(response.getOutputStream(),AttendanceDto.class).sheet(file.getOriginalFilename()).doWrite(dataList);
    }

    @Override
    public void word(MultipartFile word, MultipartFile excel, String folder) throws IOException {
        //解析Excel获取人员信息
        UserInfoListener userInfoListener = new UserInfoListener();
        EasyExcel.read(excel.getInputStream())
                .head(UserInfoDto.class)
                .registerReadListener(userInfoListener)
                .doReadAll();
        List<UserInfoDto> userList = userInfoListener.getUserList();
        if (userList.size() == 0) {
            return;
        }

        for (UserInfoDto user : userList) {
            XWPFTemplate template = XWPFTemplate.compile(word.getInputStream()).render(user);
            template.writeToFile("C:\\Users\\13246\\Desktop\\"+folder+"\\"+user.getUsername()+"_保密承诺书.docx");
        }
    }



    private Boolean isHoliday(String date){
        JinSanJjrVo jjrVoDb = jjrMapper.assertHolidayByDateTime(date);
        if (jjrVoDb != null) {
            return true;
        }
        return false;
    }

    private void randomTime1(AttendanceDto dto) {
        if (dto.getRemark() == null) {
            dto.setRemark("修改");
        }
        String rq = null;
        int num=(int) (Math.random()*30);
        if (num < 10) {
            rq = "08:0"+num;
        } else {
            rq = "08:"+num;
        }
        dto.setTime1(rq);
    }
    private void randomTime2(AttendanceDto dto) {
        if (dto.getRemark() == null) {
            dto.setRemark("修改");
        }
        String rq = null;
        int num=(int) (Math.random()*30);
        if (num < 10) {
            rq = "19:0"+num;
        } else {
            rq = "19:"+num;
        }
        dto.setTime2(rq);
    }

}
